package QianFeng07.IODemo.ByteAndCharStream;

import java.io.*;

/**
 * 指定一个盘符下的文件，把该文件复制到指定的目录下。
 *
 * 文件的复制：
 * 从一个输入流中读取数据，然后通过输出流写入目标位置
 * 一边读一边写
**/
public class CopyFileDemo {
    public static void main(String[] args) {
        copy("F:\\Test\\Test.txt", "F:\\Test\\bin1\\Test.txt");
        System.out.println("copy success");
    }

    private static void copy(String src, String target) {
        File srcFile = new File(src);
        File targetFile = new File(target);
        InputStream inputStream = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(srcFile);
            outputStream = new FileOutputStream(targetFile);

            byte[] bytes = new byte[1024];
            int len = -1;
            while ((len = inputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (inputStream != null) {
                    inputStream.close();
                }
                if (outputStream != null) {
                    outputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }

    }
}
